from django.shortcuts import render
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from random import randint
from libs.yuntongxun.sms import CCP
from rest_framework.response import Response


# Create your views here.
class RegisterImageCodeView(APIView):
    """
    实现图片验证码

    GET     /verifications/imagecodes/(?P<image_code_id>.+)/

    1. 生成图片和验证码
    2. 需要把验证码保存到redis

    """

    def get(self,request,image_code_id):

        # 1.生成图片和验证码
        text,image = captcha.generate_captcha()
        # 2.需要把验证码保存到redis
        # 连接redis
        redis_conn = get_redis_connection('code')
        # text
        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        # content_type = mime
        # text/html image/jpeg image/png

        return HttpResponse(image,content_type='image/jpeg')

#APIView
#GenericAPIView

#ListAPIView,CreateAPIView....

class RegisterSMSCodeView(GenericAPIView):
    """
    获取短信验证码

    GET     /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx

    POST    序列化器 3个字段


    1. 我们需要将用户提交的图片验证码 发送给我们,供我们校验
    2. 成功了 我们给手机号发
    3. 需要对短信进行记录
    4. 记录发送 的标记


    根据页面分析功能点 --> 我们需要哪些数据(HTTP的方式传递过来) --> 校验(确定 视图类) --> code
    """

    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):

        # 获取用户提交的数据 然后进行校验
        # 校验 --> 反序列化的一部分
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信
        sms_code = '%06d'%randint(0,999999)
        # 记录
        redis_conn = get_redis_connection('code')

        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)


        # 发送
        # ccp = CCP()

        # ccp.send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code

        # 我们的函数必须采用 函数名.delay()
        # 参数就放到 delay
        send_sms_code.delay(mobile, sms_code)
        return Response({'message':'ok'})